package com.dd.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.reggie.common.CustomException;
import com.dd.reggie.entity.Category;
import com.dd.reggie.entity.Dish;
import com.dd.reggie.entity.Employee;
import com.dd.reggie.entity.Setmeal;
import com.dd.reggie.mapper.CategoryMapper;
import com.dd.reggie.mapper.EmployeeMapper;
import com.dd.reggie.service.CategoryService;
import com.dd.reggie.service.DishService;
import com.dd.reggie.service.EmployeeService;
import com.dd.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    /**
     * 涉及到多个表的操作，应在service层进行
     * 在实现类Imply中实现remove方法
     * 目的是保证该分类下还有其他菜品或套餐存在时不能删除
     * @param id
     */
    @Autowired // 注入bean
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    @Override
    public void remove(Long id) {
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();

        //1.查询该分类下的菜品和套餐数量
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);

        int dishCount = dishService.count(dishLambdaQueryWrapper);
        int semealCount = setmealService.count(setmealLambdaQueryWrapper);

        //2.若存在菜品，则抛出业务异常
        if(dishCount > 0){
            throw new CustomException("仍存在菜品与种类相关联，抛出异常");
        }

        //3.若存在套餐，则抛出业务异常
        if(semealCount > 0){
            throw new CustomException("仍存在套餐与种类相关联，抛出异常");
        }

        //4.若无菜品与套餐关联种类，正常删除
        //super,访问父类的变量方法，this,访问当前类的变量方法
        super.removeById(id);

    }
}
